package com.chuji.crmcj.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.ClientDetailAct;
import com.chuji.crmcj.bean.FollowUpTaskInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

public class FollowTaskFragment extends Fragment {
    /*跟进任务*/
    private PullToRefreshListView lv_follow_up_task;
    //显示数据
    private LinearLayout ll_follow_up_task;
    //没有数据
    private LinearLayout ll_noData;
    /*自定义适配器*/
    private CustomFollowTaskAdapter customFollowTaskAdapter;
    /*待接待数据存储*/
    List<FollowUpTaskInfo.ApiParamObjEntity> followUpTaskTaskData;
    /*待接待网络数据*/
    private FollowUpTaskInfo followUpTaskInfo;
    //销售员ID
    String SalesID;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_follow_task, container, false);
        lv_follow_up_task= (PullToRefreshListView) view.findViewById(R.id.lv_follow_up_task);
        ll_follow_up_task= (LinearLayout) view.findViewById(R.id.ll_follow_up_task);
        ll_noData= (LinearLayout) view.findViewById(R.id.ll_noData);
        //请求数据
        initData();
        customFollowTaskAdapter=new CustomFollowTaskAdapter();
        lv_follow_up_task.setAdapter(customFollowTaskAdapter);
//        setListViewHeightBasedOnChildren(lv_follow_up_task);
        //下拉刷新
        lv_follow_up_task.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                initData();
            }
        });
        return view;
    }
    private void initData() {
        /**
         * 获得待接待任务信息
         */
        getFollowUpTaskData();
        /**
         * 获得已完成任务信息
         */
//        getEndTaskData();
    }

    private void getFollowUpTaskData() {
        //第一次
        if (followUpTaskTaskData == null) {
            followUpTaskTaskData = new ArrayList<FollowUpTaskInfo.ApiParamObjEntity>();
        }
        requestStandData();
    }
    private void requestStandData() {
        //初始化Volley
        SalesID= SPUtils.getString(UIUtils.getContext(),"UserID","");
        String strURL = String.format(UrlUtils.FOLLOW_TASK+"&SalesID="+SalesID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                followUpTaskInfo = JSON.parseObject(response, FollowUpTaskInfo.class);
                followUpTaskTaskData.addAll(followUpTaskInfo.getApiParamObj());
                if(followUpTaskInfo.getApiParamObj().size()==0){
                    ll_follow_up_task.setVisibility(View.GONE);
                    ll_noData.setVisibility(View.VISIBLE);
                }else {
                    UIUtils.runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            // 判断adapter是否创建
                            if (customFollowTaskAdapter == null) {
                                customFollowTaskAdapter = new CustomFollowTaskAdapter();
                                lv_follow_up_task.setAdapter(customFollowTaskAdapter);
//                                setListViewHeightBasedOnChildren(lv_follow_up_task);
                            } else {
                                customFollowTaskAdapter.notifyDataSetChanged();
                            }
                            lv_follow_up_task.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                    Intent intent = new Intent(UIUtils.getContext(), ClientDetailAct.class);
                                    intent.putExtra("CustomerID", followUpTaskTaskData.get(0).getCustomerID());
                                    startActivity(intent);
                                }
                            });
                        }
                    });
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    class CustomFollowTaskAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return followUpTaskTaskData.size();
        }

        @Override
        public Object getItem(int i) {
            return followUpTaskTaskData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView =  LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_follow_up_task, null);
                //初始化组件
                viewHolder.tv_client_name = (TextView) convertView.findViewById(R.id.tv_client_name);
                viewHolder.tv_client_phoneNumber = (TextView) convertView.findViewById(R.id.tv_client_phoneNumber);
                viewHolder.tv_car_type = (TextView) convertView.findViewById(R.id.tv_car_type);
                viewHolder.tv_handle_time = (TextView) convertView.findViewById(R.id.tv_handle_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tv_client_name.setText(followUpTaskTaskData.get(position).getName());
            viewHolder.tv_client_phoneNumber.setText(followUpTaskTaskData.get(position).getTel());
            viewHolder.tv_car_type.setText(followUpTaskTaskData.get(position).getCarModel());
            viewHolder.tv_handle_time.setText(followUpTaskTaskData.get(position).getCreateTime());
            return convertView;
        }
    }
    static class ViewHolder {
        private TextView tv_client_name;
        private TextView tv_client_phoneNumber;
        private TextView tv_car_type;
        private TextView tv_handle_time;
    }
//    //手动设置Listview的高度
//    public static void setListViewHeightBasedOnChildren(PullToRefreshListView listView) {
//        if (listView == null) return;
//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null) {
//            // pre-condition
//            return;
//        }
//        int totalHeight = 0;
//        for (int i = 0; i < listAdapter.getCount(); i++) {
//            View listItem = listAdapter.getView(i, null, listView);
//            listItem.measure(0, 0);
//            totalHeight += listItem.getMeasuredHeight();
//        }
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//        listView.setLayoutParams(params);
//    }
}
